import React, { FC,useState,useEffect } from 'react';
import { Form,Button,Input,TreeSelect, message } from 'antd';
import { addDirectoryInfo,getDirectoryTreeSelect } from '../../../apis/backhub/directory';

interface DirectoryAddFormProps {
  onSuccess?: () => void
}
interface Directory {
  id: number;
  name: string;
  parentId:number;
  directoryPath:string;
  createDateTime?:string;
  children?:Directory[]
}
interface BaseTree {
  title: string;
  value:string;
  children?:BaseTree[]
}
const DirectoryAddForm: FC<DirectoryAddFormProps> = ({ onSuccess }) => {
	const [treeData , setTreeData ] = useState<BaseTree[]>([]);
	const [newDirectoryName, setNewDirectoryName] = useState<string>('');
	const [directoryPath, setDirectoryPath] = useState<string>('');
	const [parentDirectoryId,setParentDirectoryId] = useState<number>(0)
	const [form] = Form.useForm();
	useEffect(() => {
	  fetchData();
	}, []);
	const fetchData = async() => {
		const treeRes = await getDirectoryTreeSelect({parentId:0})
		if(treeRes.status){
			setTreeData(treeRes.data.page)
		}
	};
	const handleSave = async() => {
		const newDirectory: Directory = { id:0,name: newDirectoryName,parentId:parentDirectoryId,directoryPath:directoryPath};
		const res = await addDirectoryInfo(newDirectory)
		if(res.status&&res.data.success){
			message.success("保存成功")
		}else{
			message.error(res.data.message)
		}
		onSuccess&&onSuccess()
	};
	return (
		<div className="upload-container">
			<Form
				form={form}
				layout="vertical"
				onFinish={handleSave}
			>
			  <Form.Item
				label="目录名称"
				name="name"
				rules={[{ required: true, message: '请输入目录名称' }]}
			  >
				<Input 
				  value={newDirectoryName} 
				  onChange={(e) => setNewDirectoryName(e.target.value)}
				/>
			  </Form.Item>
			  <Form.Item
					label="目录路径"
					name="directoryPath"
					rules={[{ required: true, message: '请输入目录路径' }]}
				>
					<Input 
					  value={directoryPath}
					  onChange={(e) => setDirectoryPath(e.target.value)}
					/>
			  </Form.Item>
			  <Form.Item
				  label="上级目录"
				  name="parentId"
				>
					<TreeSelect
				      style={{ width: '100%' }}
				      value={parentDirectoryId}
				      treeData={treeData}
				      placeholder="请选择"
				      treeDefaultExpandAll
				      onChange={setParentDirectoryId}
				    />
				</Form.Item>
			  <Form.Item>
				<Button type="primary" htmlType="submit">
				  保存
				</Button>
			  </Form.Item>
			</Form>
		</div>
	);
};

export default DirectoryAddForm;
